<template>
  <div class="chart-box" :style="chartStyles"></div>
</template>

<script>
import _ from 'lodash'
import echarts from 'echarts'
import 'echarts/extension/bmap/bmap'
import EventListener from 'utils/event-listener'
import { CHART_COLORS } from 'config/chart'

export default {
  name: 'Chart',

  props: {
    // 宽度
    width: {
      type: String,
      default: '100px'
    },

    // 高度
    height: {
      type: String,
      default: '100px'
    },

    // 是否正在加载
    loading: {
      type: Boolean,
      default: false
    },

    // 图表配置
    options: {
      type: Object,
      default () {
        return {
          series: []
        }
      }
    },

    // 图表类型
    type: {
      type: String,
      default: 'line'
    }
  },

  data () {
    return {
      chart: null
    }
  },

  computed: {
    // 图表样式
    chartStyles () {
      return {
        width: this.width,
        height: this.height
      }
    },

    // 选项
    opts () {
      let result = {
        color: CHART_COLORS
      }
      return _.merge(result, this.options)
    }
  },

  watch: {
    loading (val, oldVal) {
      if (this.chart) {
        if (val) {
          this.chart.showLoading()
        } else {
          this.chart.hideLoading()
        }
      }
    },

    options (val) {
      this.draw()
    },

    width (val) {
      this.chart.resize({
        width: val
      })
      // this.draw()
    },

    height (val) {
      this.chart.resize({
        height: val
      })
      // this.draw()
    }
  },

  mounted () {
    this.$nextTick(() => {
      this.chart = echarts.init(this.$el)
      this.bindEvent()
      this.draw()
    })
  },

  destroyed () {
    if (this.chart) {
      this.chart.dispose()
    }
    if (this.resizeEvent) {
      this.resizeEvent.remove()
    }
  },

  methods: {
    bindEvent () {
      this.resizeEvent = EventListener.listen(window, 'resize', (e) => {
        this.chart.resize()
      })
    },

    draw () {
      if (!this.chart) return
      this.$nextTick(() => {
        if (this.loading) {
          this.chart.showLoading()
        }

        this.chart.setOption(this.opts, true)
      })
    }
  }
}
</script>

<style lang="stylus">
@import '../../assets/stylus/common'

.chart-box
  position relative
  width 100%
</style>
